<?php
/*
 * @Author: your name2
 * @Date: 2021-09-21 16:46:35
 * @LastEditTime: 2022-03-10 15:00:06
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: /nlog/app/Http/Controllers/AdminController/Login.php
 */

namespace App\Http\Controllers\crm;


use Illuminate\Support\Facades\Request;
use App\Models\crm_model\CrmCustomer as CrmCustomerDb;                        // admins表
use Illuminate\Support\Facades\DB;

class CrmCustomer extends BaseController
{

    public function customerAdd()
    {
        return    redis_mysql_add('crm_customer');
    }

    public function customerEdit()
    {
        return    redis_mysql_edit('crm_customer');
    }


    public function customerSelOne()
    {
        return    redis_mysql_selone('crm_customer');
    }

    public function customerList()
    {
        // if(Request::has('division_id')){
        $whereStr = '';
        $limitStr = '';
        $keyWord = [];
        $adminInfo   = $this->getAdminInfo();

        $division_id =  $adminInfo['division_id'];                //部门id
        $admin_id    =  $adminInfo['id'];                         //自己id
        $division_name =    redis_mysql_selone_return('crm_division', $division_id, ['name'])['name']; //自己部门名称
        if (Request::input('pageSize') && Request::input('page')) {
            $limitStr =   limit_joint(Request::input('page'), Request::input('pageSize'));
        }
        if (Request::has('keyWord')) {
            $keyWord = array_filter(Request::input('keyWord'), 'filtrfunction');
        }
        $keyWord['equal-crm_customer-show'] = 1;  // 查询不为审批中的   
        if (isset($keyWord['manyField'])) {
            $whereStr .= havaWhereLikeManyField($keyWord['manyField']);
            unset($keyWord['manyField']);
        }
        if (!empty($keyWord)) {
            $whereStr .= havaWhereLikeJoinEqual($keyWord);
        }

        $list  =  CrmCustomerDb::crmCustomerList($admin_id, $division_id,  $division_name, $whereStr, $limitStr);
        $count =  CrmCustomerDb::crmCustomerCount($admin_id, $division_id,  $division_name, $whereStr);
        return $this->create(200, '查询成功', ['list' => $list, 'total' => $count[0]['count']]);
        // }
    }

    //客户池列表
    public function customerPool()
    {
        // if(Request::has('division_id')){
        $whereStr = '';
        $limitStr = '';
        $keyWord  = [];
        $adminInfo   = $this->getAdminInfo();
        if (Request::input('pageSize') && Request::input('page')) {
            $limitStr =   limit_joint(Request::input('page'), Request::input('pageSize'));
        }
        if (Request::has('keyWord')) {
            $keyWord = array_filter(Request::input('keyWord'), 'filtrfunction');
        }
        $keyWord['equal-crm_customer-show'] = 1;  // 查询不为审批中的   
        if (isset($keyWord['manyField'])) {
            $whereStr .= havaWhereLikeManyField($keyWord['manyField']);
            unset($keyWord['manyField']);
        }
        if (!empty($keyWord)) {
            $whereStr .= havaWhereLikeJoinEqual($keyWord);
        }

        $list  =  CrmCustomerDb::customerPoolList($adminInfo['division_id'],   $whereStr, $limitStr);
        $count =  CrmCustomerDb::customerPoolCount($adminInfo['division_id'],   $whereStr);
        return $this->create(200, '查询成功', ['list' => $list, 'total' => $count[0]['count']]);
        // }
    }



    public function customerChange()
    {
        if (Request::has('customer') && Request::has('remark') &&  Request::has('after_admins_id') && Request::has('update_time') && Request::has('division_id') && Request::has('after_division_id') && Request::has('before_admins_id')) {
            $after_admins_id = Request::input('after_admins_id');
            $customer = Request::input('customer');
            $remark = Request::input('remark');
            $update_time = Request::input('update_time');
            $division_id = Request::input('division_id');
            $after_division_id = Request::input('after_division_id');
            $before_admins_id = Request::input('before_admins_id');
            if ($after_admins_id === 0) {   //等于0时直接加入客户池
                $message = '转移成功';
                if (is_array($customer)) {
                    for ($i = 0; $i < count($customer); $i++) {        //当为数组时
                        $data = $customer[$i];
                        go(function () use ($data, $after_division_id, $remark) {
                            redis_mysql_edit_return('crm_customer', ['id' => $data['id'], 'update_time' => $data['update_time']], ['in_pool_time' => date('Y-m-d H:i:s'), 'division_id' => $after_division_id, 'pool_remark' => $remark, 'show' => 1], '', false,  false, false);
                        });
                    }
                    $res = true;
                } else {
                    $res =  redis_mysql_edit_return('crm_customer', ['id' => $customer, 'update_time' => $update_time], ['in_pool_time' => date('Y-m-d H:i:s'), 'division_id' => $after_division_id, 'pool_remark' => $remark, 'show' => 1], '', false,  false, false);
                }
            } else {   //转移给其他人
                if ($division_id === 0) {      //  不需要审批 审批部门id
                    $message = '转移成功';
                    if (is_array($customer)) {
                        for ($i = 0; $i < count($customer); $i++) {        //当为数组时
                            $data = $customer[$i];
                            go(function () use ($data, $after_admins_id, $after_division_id) {
                                redis_mysql_edit_return("crm_customer", ['id' => $data['id'], 'update_time' => $data['update_time']], ['show' => 1, 'division_id' => $after_division_id, 'in_pool_time' => null, 'admins_id' => $after_admins_id], '', false,  false, false);
                            });
                        }
                        $res = true;
                    } else {
                        $res =  redis_mysql_edit_return("crm_customer", ['id' => $customer, 'update_time' => $update_time], ['show' => 1, 'division_id' => $after_division_id, 'in_pool_time' => null, 'admins_id' => $after_admins_id], '', false,  false, false);
                    }
                } else {               //需要审批 
                    $message = '提交申请成功,请上级审批';
                    if (is_array($customer)) {
                        for ($i = 0; $i < count($customer); $i++) {        //当为数组时
                            $data = $customer[$i];
                            go(function () use ($data, $before_admins_id, $division_id, $remark, $after_admins_id, $after_division_id) {
                                DB::beginTransaction();
                                try {
                                    $res =  redis_mysql_edit_return("crm_customer", ['id' => $data['id'], 'update_time' => $data['update_time']], ['show' => 0], '', false,  false, false);
                                    if ($res) {
                                        $res =  redis_mysql_add_return("transfer_apply_for", ["admins_id" => $this->getAdminId(), "customer_id" => $data['id'], "before_admins_id" => $before_admins_id, "after_admins_id" => $after_admins_id, "after_division_id" => $after_division_id, "division_id" => $division_id, "remark" => $remark], '', false, 'id', false);
                                    } else {
                                        DB::rollBack();
                                    }
                                    DB::commit();
                                } catch (\Exception $e) {
                                    DB::rollBack();
                                    $res = false;
                                }
                            });
                        }
                        $res = true;
                    } else {
                        DB::beginTransaction();
                        try {
                            $res =  redis_mysql_edit_return("crm_customer", ['id' => $customer, 'update_time' => $update_time], ['show' => 0], '', false,  false, false);
                            if ($res) {
                                $res =  redis_mysql_add_return("transfer_apply_for", ["admins_id" => $this->getAdminId(), "customer_id" => $customer, "before_admins_id" => $before_admins_id, "after_admins_id" => $after_admins_id, "after_division_id" => $after_division_id, "division_id" => $division_id, "remark" => $remark], '', false, 'id', false);
                            } else {
                                DB::rollBack();
                            }
                            DB::commit();
                        } catch (\Exception $e) {
                            DB::rollBack();
                            $res = false;
                        }
                    }
                }
            }

            if ($res) {
                return $this->create(200, $message);
            } else {
                return $this->create(100, '该客户在其他地方已被操作');
            }
        }
    }



    /**
     * @description: 客户审批列表
     * @param {*}
     * @return {*}
     */
    public function customerApplyList()
    {


        $whereStr = '';
        $limitStr = '';
        $keyWord = [];
        $adminInfo   = $this->getAdminInfo();

        $division_id =  $adminInfo['division_id'];                //部门id
        // $division_name =    redis_mysql_selone_return('crm_division', $division_id, ['name'])['name']; //自己部门名称
        if (Request::input('pageSize') && Request::input('page')) {
            $limitStr =   limit_joint(Request::input('page'), Request::input('pageSize'));
        }
        if (Request::has('keyWord')) {
            $keyWord = array_filter(Request::input('keyWord'), 'filtrfunction');
        }
        // $keyWord['equal-crm_customer-show'] = 1;  // 查询不为审批中的   
        if (isset($keyWord['manyField'])) {
            $whereStr .= havaWhereLikeManyField($keyWord['manyField']);
            unset($keyWord['manyField']);
        }
        if (!empty($keyWord)) {
            $whereStr .= havaWhereLikeJoinEqual($keyWord);
        }

        $list  =  CrmCustomerDb::customerApplyList($division_id, $whereStr, $limitStr);
        $count =  CrmCustomerDb::customerApplyCount($division_id, $whereStr);
        return $this->create(200, '查询成功', ['list' => $list, 'total' => $count[0]['count']]);
    }


    public function customerManyEdit()
    {
        if (Request::has('multipleSelection') && Request::has('formData')) {
            $multipleSelection = Request::input('multipleSelection');
            $formData = Request::input('formData');
            $array = [];
            $array_id = [];
            DB::beginTransaction();
            try {
                for ($i = 0; $i < count($multipleSelection); $i++) {
                    $array_id[] = $multipleSelection[$i]['id'];
                    $array[] = array('customer_id' => $multipleSelection[$i]['crm_customer_id'], 'after_division_id' => $multipleSelection[$i]['after_division_id'], 'after_admins_id' =>  $multipleSelection[$i]['after_admins_id']);
                }
                redis_mysql_edit_in("transfer_apply_for", $array_id, $formData);
                DB::commit();
            } catch (\Exception $e) {
                DB::rollBack();
                return $this->create(100, '修改失败');
            }
            if (isset($formData['status']) && !empty($array)) {
                if ($formData['status'] == 2) {
                    for ($i = 0; $i < count($array); $i++) {
                        $tmp = $array[$i];
                        go(function () use ($tmp) {
                            redis_mysql_edit_return("crm_customer", array('id' => $tmp['customer_id']),  ['show' => 1, 'in_pool_time' => null, 'admins_id' => $tmp['after_admins_id'], 'division_id' => $tmp['after_division_id']]);
                        });
                    }
                } else if ($formData['status'] == 0) {
                    for ($i = 0; $i < count($array); $i++) {
                        $tmp = $array[$i];
                        go(function () use ($tmp) {
                            redis_mysql_edit_return("crm_customer", array('id' => $tmp['customer_id']),  ['show' => 1]);
                        });
                    }
                }
            } else {
                return $this->create(100, '修改失败');
            }
            return $this->create(200, '修改成功');
        }
    }


    public function   customerLinkmanId(){
        if(Request::has('linkman_id')){
            $linkman_id = Request::input('linkman_id');
            $res =  CrmCustomerDb::customerLinkmanId( $linkman_id);
            $data = [];
            if($res){
                $data =    array_map(fn($item) => $item['id'] ,$res);
            }
            return $this->create(200,'查询成功',$data);
        }
    }
}
